import { defineStore } from "pinia";
import CommonApi from "@/api/common.js";

export const useConfigStore = defineStore(
  "config",
  () => {
    const systemBarHeight = ref(0);
    const loginRole = ref("1"); // 1家长 2教师
    const areaList = ref({});

    const getAreaList = async (parentCode) => {
      console.log("获取地区列表parentCode:", parentCode);
      // areaList.value = (await uni.getStorageSync("areaList")) || {};

      if (!areaList.value || !areaList.value[parentCode]) {
        const res = await CommonApi.selectByParentCode({ parentCode });
        areaList.value[parentCode] = res.map((item) => {
          return {
            label: item.name,
            value: item.code,
            parentCode: item.parentCode,
          };
        });
        parentCode = areaList.value[parentCode][0].value;
      }
      // 获取的是省=>市
      if (parentCode.length === 2 && !areaList.value[parentCode]) {
        const res = await CommonApi.selectByParentCode({ parentCode });

        areaList.value[parentCode] = res.map((item) => {
          return {
            label: item.name,
            value: item.code,
            parentCode: item.parentCode,
          };
        });
        parentCode = areaList.value[parentCode][0].value;
      }
      if (parentCode.length === 4 && !areaList.value[parentCode]) {
        const res = await CommonApi.selectByParentCode({ parentCode });

        areaList.value[parentCode] = res.map((item) => {
          return {
            label: item.name,
            value: item.code,
            parentCode: item.parentCode,
          };
        });
      }
      // uni.setStorageSync("areaList", areaList.value);
      return areaList.value;
    };
    const switchRole = (role: string) => {
      console.log("切换角色", role);
      loginRole.value = role;
    };

    const getSysteminfo = () => {
      try {
        // const storedHeight = uni.getStorageSync("navbarHeight");
        if (systemBarHeight.value <= 0) {
          uni.getSystemInfo({
            success: (res) => {
              systemBarHeight.value = res.statusBarHeight;
              // uni.setStorageSync("navbarHeight", res.statusBarHeight);
              // systemBarHeight.value = storedHeight;
              console.log("系统信息", res);
            },
          });
        }
      } catch (error) {
        console.error("获取系统信息失败:", error);
      }
    };

    // 立即执行
    getSysteminfo();

    return {
      systemBarHeight,
      getSysteminfo,
      loginRole,
      switchRole,
      areaList,
      getAreaList,
    };
  },
  {
    persist: true,
  },
);
